<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" v-model="keyword" placeholder="请输入管理员名"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleFind">查找</el-button>
      <el-button type="primary" @click="handleAdd" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="tableData" v-loading="Loading" style="width: 100%" stripe>
      <el-table-column label="序号" width="60" align="center">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.headUrl" fit="cover"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column label="邮箱" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>

      <el-table-column label="昵称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="拥有角色" align="center">
        <template slot-scope="scope">
          <el-tag :key="index" v-for="(item, index) in scope.row.rolesList" type="danger">{{item.name}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" min-width="160" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.registerTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" min-width="250" align="center">
        <template slot-scope="scope">
<!--          <el-button @click="handRest(scope.row)" type="warning" size="small">重置密码</el-button>-->
          <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
          <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="block">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <el-dialog :title="title" v-if="dialogFormVisible" :visible.sync="dialogFormVisible" :close-on-click-modal='false' :before-close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="头像" :label-width="formLabelWidth">
          <div style="width:100px;height:100px;cursor: pointer;" @click="showCutter=true">
            <el-avatar :src="form.headUrl" shape="square" icon="el-icon-plus" :size="100"></el-avatar>
          </div>
        </el-form-item>

        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleUid">
              <el-select v-model="addRoleId" multiple placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="10">
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
              <el-input type="password" v-model="form.password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- Element的z-index（默认值：2000） -->
    <avatar-cutter style="z-index:3000" v-if="showCutter" @cancel="showCutter = false" return-type="file" @enter="uploadAvatar"></avatar-cutter>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { uploadFile, addPicture } from "@/api/picture";
import { getRoleList } from "@/api/role";
import {
  getAdminList,
  addAdmin,
  editAdmin,
  deleteAdmin,
  restPwdAdmin,
} from "@/api/admin";
import AvatarCutter from "../../components/avatar-cutter/avatar-cutter";
export default {
  components: {
    AvatarCutter,
  },
  data() {
    return {
      Loading: true,
      VUE_APP_IMAGE_URL: process.env.VUE_APP_IMAGE_URL,
      avatarSortUid: "6f041dff94ff28c9f8d4bef882844003", //头像相册分类得uid
      tableData: [],
      roleOptions: [], //角色候选框
      keyword: "",
      currentPage: 1,
      pageSize: 10,
      total: 0, //总数量
      addRoleId: null, // from表单的roleId
      form: {
        id: null,
        username: null,
        headUrl: null,
        email: null,
        password: null,
        userRoleList: null
      },
      dialogFormVisible: false,
      title: "添加管理员",
      formLabelWidth: "120px",
      isEditForm: false,
      showCutter: false, // 是否显示头像裁剪组件
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度为1到20个字符" },
        ],
        email: [
          {
            pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ]
      },
    };
  },
  created() {
    this.roleList();
    this.adminList();
  },
  methods: {
    adminList() {
      this.Loading = true;
      var params = {};
      params.index = this.currentPage;
      params.size = this.pageSize;
      getAdminList(params).then((response) => {
          this.tableData = response.data.data.result;
          this.total = response.data.data.total;
          this.Loading = false;
      });
    },
    handleFind() {
      this.adminList();
    },
    handleAdd() {
      this.title = "增加管理员";
      this.addRoleId = []
      this.dialogFormVisible = true;
      this.isEditForm = false;
    },
    handleEdit(row) {
      this.form = Object.assign(this.form, row);
      this.addRoleId = []
      for(var role of this.form.rolesList)
        this.addRoleId.push(role.roleId)
      this.title = "编辑管理员";
      this.dialogFormVisible = true;
      this.isEditForm = true;
    },
    handleDelete(row) {
      this.$confirm("此操作将该管理员删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAdmin(row.id).then((response) => {
              this.$message({
                type: "success",
                message: response.data,
              });
            this.adminList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange() { },
    handleDialogClose() {
      this.form = {
        id: null,
        username: null,
        headUrl: null,
        email: null,
        password: null,
        userRoleList: null
      };
      this.dialogFormVisible = false;
    },
    uploadAvatar(src) {
      var formData = new FormData();
      formData.append("file", src);
      // formData.append("userUid", this.$store.getters.userUid);
      // formData.append("sortName", "admin");
      uploadFile(formData).then((response) => {
        this.form.headUrl = response.data.data;
        this.showCutter = false;
      });
    },
    // //角色远程搜索函数
    roleList() {
      getRoleList().then((response) => {
        this.roleOptions = response.data.data;
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.userRoleList = []
          for( var roleId of this.addRoleId){
            this.form.userRoleList.push({"roleId":roleId})
          }
          if (this.isEditForm) {
            editAdmin(this.form).then((response) => {
                if (this.form.userName === this.$store.getters.userName) {
                  this.$store.commit("user/SET_AVATAR", this.form.photoList);
                }
                this.$message({
                  type: "success",
                  message: response.data,
                });
                this.handleDialogClose();
                this.adminList();
            });
          } else {
            addAdmin(this.form).then((response) => {
                this.$message({
                  type: "success",
                  message: response.data,
                });
                this.handleDialogClose();
                this.adminList();
            });
          }
        }
      });
    },
  },
};
</script>
